import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/regional_organization_tree/regional_organization_tree_view.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/common/department_user_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/common/risk_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/get_target_tasking_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/danger_investigation_page/danger_investigation_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///任务分配待分配
class TaskAllocationAllocatedController extends GetxController {
  /// 选中的节点
  RiskTreeEntity selectedEntity = RiskTreeEntity();

  /// 搜索字符串
  String? searchX = '';

  ///已选择的累计 反之减
  int addCount = 0;

  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 筛选后的层级id  需要筛选后的层级id 默认id ALL
  String levelMeasuresId = 'all';

  /// 筛选后的level 	当前层级:当前层级：全部,1，对象,2，单元,3，事件,4,措施，5
  int? level = 1;

  ///筛选按钮
  void onFilterButtonPressed() {
    final DangerInvestigationController controller = Get.find<DangerInvestigationController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    // riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  void isBool() {
    update();
  }

  //详情
  void onClickDetail(String? id) {
    Get.toNamed(AppRoutes.allocationDetailsTwoPage, arguments: id);
  }

  Future<List<GetTargetTaskingEntity>> getTaskListAPP(int index, int size, {String? search}) async {
    final res = await HttpUtil().generateGetRequest<List<GetTargetTaskingEntity>>(
      Interface.getTaskListAPP,
      queryParameters: {
        'id': levelMeasuresId,
        'level': level,
        'pageNum': index,
        'pageSize': 5,
        'troubleshootContent': searchX,
      },
    ).execute();
    List<GetTargetTaskingEntity>? list = [];
    res.onSuccess((result) {
      if (result.data != null) {
        list = result.data;
      }
    });
    if (index == 1) {
      addCount = 0;
      measuresTaskIdsCount.clear();
      update();
    }
    return list!;
  }

  ///统计请求的请求体
  List<String> measuresTaskIdsCount = [];

  ///  添加分配（为部门分配任务）
  void addAllocationBaseMeasures(DepartmentUserTreeEntity selected) async {
    final res = await HttpUtil().generatePostRequest(
      Interface.allocationBaseMeasures,
      data: {
        'allocationId': selected.id, //	任务分配目标id    筛选里的数据 583ca908-2489-4a66-acd8-ede957252c4f
        'allocationName': selected.departmentName, //任务分配目标名称   筛选里的数据
        'allocationType': '2', //任务分配目标类型，1个人，2部门 默认部门
        'measuresTaskIds': measuresTaskIdsCount, //排查任务编号列表    当前列表里的数据
      },
    ).execute();
    res.onSuccess((result) {
      AppToast.showError('添加成功');
      globalKey.currentState?.onRefresh();
    });
    res.onError((result) {
      AppToast.showError('添加失败');
    });
  }

  // 搜索
  void refreshPage() {
    globalKey.currentState?.onRefresh();
  }

  // 重置
  void reset() {
    levelMeasuresId = 'all';
    level = 1;
    Get.find<DangerInvestigationController>(). riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = RiskTreeEntity();
    globalKey.currentState!.onRefresh();
    update();
  }

  // 确定
  void confirm() {
    Get.back();
    //筛选里的任意层级的id
    levelMeasuresId = selectedEntity.id!;
    level = selectedEntity.level!;
    globalKey.currentState!.onRefresh();
    update();
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          RegionalOrganizationTreePage(
            selectedEntity: selectedEntity,
            onCallBack: (RiskTreeEntity entity) {
              selectedEntity = entity;
            },
          )
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }
}
